<template>
  <div class="app-container">
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick" v-if="isUserOrRecycle">
      <el-tab-pane label="个人文档" name="personal">
        <el-row :gutter="20">
          <el-col :lg="4" :xs="24" style="">
            <el-card shadow="hover">
              <!-- <el-input v-model="deptName" placeholder="请输入部门名称" prefix-icon="Search" clearable /> -->
              <el-tree ref="deptTreeRef" class="mt-2" node-key="id" :data="deptOptions"
                :props="{ label: 'label', children: 'children' }" :expand-on-click-node="false"
                :filter-node-method="filterNode" highlight-current default-expand-all @node-click="handleNodeClick" />
            </el-card>
          </el-col>
          <el-col :lg="20" :xs="24">
            <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
              :leave-active-class="proxy?.animate.searchAnimate.leave">
              <div v-show="showSearch" class="mb-[10px]">
                <el-card shadow="hover">
                  <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                    <el-form-item label="用户名称" prop="userName">
                      <el-input v-model="queryParams.userName" placeholder="请输入用户名称" clearable
                        @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item label="手机号码" prop="phonenumber">
                      <el-input v-model="queryParams.phonenumber" placeholder="请输入手机号码" clearable
                        @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item label="创建时间" style="width: 308px">
                      <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                        :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"></el-date-picker>
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                      <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                  </el-form>
                </el-card>
              </div>
            </transition>
            <el-card shadow="hover">
              <el-table v-loading="loading" :data="userList" @row-click="handleRowClick">
                < <el-table-column v-if="columns[0].visible" key="userId" label="用户编号" align="center" prop="userId" />
                <el-table-column v-if="columns[1].visible" key="userName" label="用户名称" align="center" prop="userName"
                  :show-overflow-tooltip="true" width="120" />
                <el-table-column v-if="columns[2].visible" key="nickName" label="用户昵称" align="center" prop="nickName"
                  :show-overflow-tooltip="true" />
                <el-table-column v-if="columns[3].visible" key="sex" label="性别" align="center" prop="sex"
                  :show-overflow-tooltip="true" width="120">
                  <template #default="scope">
                    {{ scope.row.sex == '0' ? '男' : '女' }}
                  </template>
                </el-table-column>
                <el-table-column v-if="columns[4].visible" key="phonenumber" label="电话" align="center"
                  prop="phonenumber" width="120" />
                <el-table-column v-if="columns[5].visible" key="email" label="邮箱" align="center" prop="email" />
                <el-table-column v-if="columns[6].visible" key="deptName" label="部门" align="center" prop="deptName"
                  :show-overflow-tooltip="true" />

                <el-table-column v-if="columns[7].visible" label="创建时间" align="center" prop="createTime" width="160">
                  <template #default="scope">
                    <span>{{ scope.row.createTime }}</span>
                  </template>
                </el-table-column>


              </el-table>

              <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
                :total="total" @pagination="getList" />
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="团队文档" name="team">
        <el-table ref="tableRef" :data="teamList" @row-dblclick="handleRowDblClick">
          <el-table-column prop="teamName" label="团队名称">
            <template #default="scope">
              <svg-icon icon-class="xiangmutuandui" style="
                      font-size: 20px;
                      vertical-align: middle;
                    " />
              <span style="margin-left: 10px;" class="realName_class">{{ scope.row.teamName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="ownerName" label="团队管理员" align="center"></el-table-column>
          <el-table-column prop="createTime" label="修改时间" align="center"></el-table-column>
        </el-table>
        <pagination v-show="teamRqs.total > 0" v-model:page="teamRqs.page" v-model:limit="teamRqs.size"
          :total="teamRqs.total" @pagination="getTeamList" />
      </el-tab-pane>
      <el-tab-pane label="企业文档" name="enterprise">企业文档</el-tab-pane>

    </el-tabs>
    <div class="dataPa" v-show="!isUserOrRecycle">
      <el-button type="primary" :icon="ArrowLeft" @click="backUsersClick" plain>返回</el-button>
      <second-recycle-table ref="recyclePersonalRefs" :rowData="rowData" :tabsType="tabsType"></second-recycle-table>

    </div>
  </div>
</template>


<script setup lang="ts">
import { ref } from 'vue'
import api from '@/api/system/user'
import type { TabsPaneContext } from 'element-plus'
import { DeptVO } from '@/api/system/dept/types'
import { UserForm, UserQuery, UserVO } from '@/api/system/user/types'
import { ArrowLeft } from '@element-plus/icons-vue'
import SecondRecycleTable from './components/second-recycle-table.vue'
import { apiTeamQuery } from '@/api/fileManage/secondaryRecycle/index'

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const showSearch = ref(true)
const teamList = ref([])
const teamRqs = reactive({
  page: 1,
  size: 10,
  total: 0
})



const isUserOrRecycle = ref(true)
const activeName = ref('personal')
const deptName = ref('')
const deptOptions = ref<DeptVO[]>([])
const initFormData: UserForm = {
  userId: undefined,
  deptId: undefined,
  userName: '',
  nickName: undefined,
  password: '',
  phonenumber: undefined,
  email: undefined,
  sex: undefined,
  status: '0',
  remark: '',
  postIds: [],
  roleIds: []
}
const initData: PageData<UserForm, UserQuery> = {
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: '',
    phonenumber: '',
    status: '',
    deptId: '',
    roleId: ''
  },
  rules: {
    userName: [
      { required: true, message: '用户名称不能为空', trigger: 'blur' },
      {
        min: 2,
        max: 20,
        message: '用户名称长度必须介于 2 和 20 之间',
        trigger: 'blur'
      }
    ],
    nickName: [{ required: true, message: '用户昵称不能为空', trigger: 'blur' }],
    password: [
      { required: true, message: '用户密码不能为空', trigger: 'blur' },
      {
        min: 5,
        max: 20,
        message: '用户密码长度必须介于 5 和 20 之间',
        trigger: 'blur'
      },
      { pattern: /^[^<>"'|\\]+$/, message: '不能包含非法字符：< > " \' \\\ |', trigger: 'blur' }
    ],
    email: [
      {
        type: 'email',
        message: '请输入正确的邮箱地址',
        trigger: ['blur', 'change']
      }
    ],
    phonenumber: [
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: '请输入正确的手机号码',
        trigger: 'blur'
      }
    ],
    roleIds: [{ required: true, message: '用户角色不能为空', trigger: 'blur' }]
  }
}
// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `用户编号`, visible: false, children: [] },
  { key: 1, label: `用户名`, visible: true, children: [] },
  { key: 2, label: `昵称`, visible: true, children: [] },
  { key: 3, label: `性别`, visible: true, children: [] },
  { key: 4, label: `电话`, visible: true, children: [] },
  { key: 5, label: `邮箱`, visible: true, children: [] },
  { key: 6, label: `部门`, visible: true, children: [] },
  { key: 7, label: `创建日期`, visible: true, children: [] },

])
const data = reactive<PageData<UserForm, UserQuery>>(initData)
const { queryParams, form, rules } = toRefs<PageData<UserForm, UserQuery>>(data)
const userList = ref<UserVO[]>([])
const total = ref(0)
const loading = ref(true)
const dateRange = ref([])
const deptTreeRef = ref()
const queryFormRef = ref<ElFormInstance>()

const rowData = ref({})
const tabsType = ref('personal')

onMounted(() => {
  getTreeSelect() // 初始化部门数据
  getList() // 初始化列表数据

})



/** 查询部门下拉树结构 */
const getTreeSelect = async () => {
  const res = await api.deptTreeSelect()
  deptOptions.value = res.data
}
const handleClick = (tab: TabsPaneContext, event: Event) => {
  activeName.value = tab.props.name as string
  tabsType.value = tab.props.name as string
  if (activeName.value == 'enterprise') {
    isUserOrRecycle.value = false
  } else {
    isUserOrRecycle.value = true
  }
  if (activeName.value == 'team') {
    getTeamList()
  }
}
/** 通过条件过滤节点  */
const filterNode = (value: string, data: any) => {
  if (!value) return true
  return data.label.indexOf(value) !== -1
}

// 点击查询回收站数据
const handleRowClick = async (row: UserVO) => {
  rowData.value = row
  tabsType.value = "personal"
  isUserOrRecycle.value = false

}

const backUsersClick = async () => {
  if (activeName.value == "enterprise") {
    activeName.value = "personal"
    tabsType.value = "personal"
  }
  if (activeName.value == "team") {
    activeName.value = "personal"
    tabsType.value = "personal"
  }
  // tabsType.value = "enterprise"
  isUserOrRecycle.value = true
}

/** 查询用户列表 */
const getList = async () => {
  loading.value = true
  const res = await api.listUser(proxy?.addDateRange(queryParams.value, dateRange.value))
  loading.value = false
  userList.value = res.rows
  total.value = res.total
}
/** 节点单击事件 */
const handleNodeClick = (data: DeptVO) => {
  queryParams.value.deptId = data.id
  handleQuery()
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
}
/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', '']
  queryFormRef.value?.resetFields()
  queryParams.value.pageNum = 1
  queryParams.value.deptId = undefined
  deptTreeRef.value?.setCurrentKey(undefined)
  handleQuery()
}
const getTeamList = async () => {
  const res = await apiTeamQuery({
    page: teamRqs.page - 1,
    size: teamRqs.size,
    type: 0
  })
  if (res.code == 200) {
    teamList.value = res.data.rows
    teamRqs.total = res.data.total
  }
}

const handleRowDblClick = (row: any) => {
  rowData.value = row
  tabsType.value = "team"
  isUserOrRecycle.value = false
}
</script>